<?php

namespace App\Http\Controllers\Wap;


use App\Http\Controllers\Api\ApiController;
use App\Models\AdminParam;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Laravel\Socialite\Facades\Socialite;


class LoginController extends ApiController
{

    // 生成token
    public function buildToken($user)
    {
        $token = str_random(60);
        $expiredAt = now()->addDays(2);
        \Cache::put($token, $user, $expiredAt);
        return $token;
    }

    // wap登录
    public function login(Request $request)
    {
        $phone = trim($request->get('phone'));

        $verifyData = \Cache::get($request->verify_key);
        if (!$verifyData) {
            return $this->failed('验证码已失效');
        }
        if (!hash_equals($verifyData['code'], $request->verify_code)) {
            return $this->failed('验证码错误');
        }
        $phone = $verifyData['phone'];

        // 查询手机号用户是否存在
        $user = User::where('phone', $phone)->first();

        // 判断登录是否有token传递进来
        $header = $request->header('authorization');
        $token = trim(preg_replace('/^(?:\s+)?Bearer\s/', '', $header));
        if ($user) {
            // 如果手机号用户存在，有授权
            // 否则手机号用户存在，没有授权，直接返回用户信息
            if (\Cache::has($token)) {
                $user_token = \Cache::get($token);
                // 如果手机号用户存在，且用户没有绑定微信openid
                // 否则就是 => 手机号用户存在，且用户绑定微信openid，直接返回用户信息
                if ($user_token->weixin_openid == '') {
                    $user->weixin_openid = $user_token->weixin_openid;
                    $user->name = $user_token->name;
                    $user->weixin_head_image_path = $user_token->weixin_head_image_path;
                    $user->save();
                }
            }
        } else {
            // 如果手机号用户不存在, 有授权
            // 如果手机号用户不存在, 没有授权， 就创建新用户
            if (\Cache::has($token)) {
                $user = \Cache::get($token);
                // 如果授权里有用户openid信息，就把手机号绑定到此微信id
                $user->phone = $phone;
                $user->free_diagnosis = 1;      // 绑定手机号，赠送一次免费查看
                $user->save();
            } else {
                $user = User::create([
                    'phone'          => $phone,
                    'free_diagnosis' => 1,      // 绑定手机号，赠送一次免费查看
                ]);
            }
        }

        $user->last_login_at = Carbon::now();
        $user->save();
        // 创建token
        $token = $this->buildToken($user);

        // 清除验证码缓存
        \Cache::forget($request->verify_key);

        return $this->success(['token' => $token]);
    }

    // 社会化登录 / 三方登录
    public function socialLogin($type, Request $request)
    {
        // 第一步：请求CODE => https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb1059b84b6178bc9&redirect_uri=http://carwap.dmdoit.com/ss&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
        // 第二步：通过code获取access_token => https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxb1059b84b6178bc9&secret=72b9405f2a89386f8587235ff3d4892e&code=0010C15y0Gr8ad13Zm5y0ere5y00C15x&grant_type=authorization_code
        // 获取用户个人信息（UnionID机制）=> https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
        // unionid	只有在用户将公众号绑定到微信开放平台帐号后，才会出现该字段。

        if (!in_array($type, ['weixin'])) {
            return $this->failed('登录方式不被允许');
        }

        $driver = Socialite::driver($type);

        try {
            // 支持2种情况： (注意 => 一个code码只能够使用一次)
            // 1、（客户端只有 code授权码），来获取 access_token 和 openid
            // 2、（客户端已经得到 access_token 和 openid），来获取用户信息
            if ($code = $request->code) {
                $response = $driver->getAccessTokenResponse($code);
                $token = array_get($response, 'access_token');
            } else {
                $token = $request->access_token;
                if ($type == 'weixin') {
                    $driver->setOpenId($request->openid);
                }
            }
            // 获取微信用户信息
            $oauthUser = $driver->userFromToken($token);
        } catch (\Exception $e) {
            return $this->failed($e->getMessage());
            //return $this->failed('参数错误，未获取用户信息');
        }

        switch ($type) {
            case 'weixin':
                $unionid = $oauthUser->offsetExists('unionid') ? $oauthUser->offsetGet('unionid') : null;

                if ($unionid) {
                    $user = User::where('weixin_unionid', $unionid)->first();
                } else {
                    $user = User::where('weixin_openid', $oauthUser->getId())->first();
                }

                // 没有用户，默认创建一个用户
                if (!$user) {
                    $user = User::create([
                        'name'                   => $oauthUser->getNickname(),
                        'weixin_head_image_path' => $oauthUser->getAvatar(),
                        'weixin_openid'          => $oauthUser->getId(),
                        'weixin_unionid'         => $unionid,
                    ]);
                }
                break;
        }

        $user->last_login_at = Carbon::now();
        $user->save();

        $token = $this->buildToken($user);

        return $this->success($token);
    }


    public function logout()
    {
//        if (\Auth::guard('api')->check()) {
////            \Auth::guard('api')->user()->token()->revoke();
//            \Auth::guard('api')->user()->token()->delete();
//        }

        return $this->message('退出登录成功');
    }

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'email'    => 'required|email',
            'password' => 'required|string|min:6',
        ], [
            'email.required'    => '请输入邮箱',
            'email.email'       => '邮箱格式不正确',
            'password.required' => '请输入密码',
            'password.min'      => '密码长度至少是6位',
        ]);
    }

}
